package com.gzhryc.shared_device.oem.h5.mng.controllers.pcl;

import com.gzhryc.common.MatrixToImageWriter;
import com.gzhryc.common.StringTools;
import com.gzhryc.common.config.PropertyTools;
import com.gzhryc.common.data.dto.AjaxResult;
import com.gzhryc.common.data.dto.ListResult;
import com.gzhryc.common.exceptions.LogicException;
import com.gzhryc.common.logging.Logger;
import com.gzhryc.servlet.DtoConstants;
import com.gzhryc.servlet.WebUtils;
import com.gzhryc.servlet.annotation.Route;
import com.gzhryc.shared_device.common.BusyThreadPool;
import com.gzhryc.shared_device.common.device.dao.db.Device;
import com.gzhryc.shared_device.common.device.dao.db.DeviceType;
import com.gzhryc.shared_device.common.device.dao.db.DeviceTypeFunc;
import com.gzhryc.shared_device.common.device.services.DeviceService;
import com.gzhryc.shared_device.common.device.services.DeviceTypeFuncService;
import com.gzhryc.shared_device.common.device.services.DeviceTypeService;
import com.gzhryc.shared_device.oem.code.device.EDeviceFunCode;
import com.gzhryc.shared_device.oem.h5.mng.WebConstants;
import com.gzhryc.shared_device.pcl.code.dao.db.ChargingCable;
import com.gzhryc.shared_device.pcl.code.dao.enums.ChargingCableEnum;
import com.gzhryc.shared_device.pcl.code.services.ChargingCableService;
import com.gzhryc.shared_device.pcl.code.services.dto.ChargingCableSearch;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

public class ChargingCableController {

    static Logger log = Logger.getLogger(ChargingCableController.class);

    @Route("/pcl/device/list.html")
    public String list(HttpServletRequest request) {
        request.setAttribute("stateList", ChargingCableEnum.State.values());
        List<String> deviceTypeIds = DeviceTypeFuncService.self().findTypeIdByCode(EDeviceFunCode.PCL.index());
        List<DeviceType> deviceTypeList = DeviceTypeService.self().findByIds(deviceTypeIds);
        if(deviceTypeList != null){
            request.setAttribute("deviceTypeList", deviceTypeList);
        }
        return "/pcl/device/list.html";
    }

    @Route(value = "/pcl/device/list.data")
    public ListResult<ChargingCable> listData(HttpServletRequest request) {
        ListResult<ChargingCable> result = new ListResult<>(DtoConstants.NULL_DATA,"暂无数据");
        ChargingCableSearch search = WebUtils.getParameter(request, ChargingCableSearch.class);
        Integer pageNo = WebUtils.getInteger(request, "page", 1);
        Integer pageLimit = WebUtils.getInteger(request, "limit", WebConstants.PAGE_LIMIT);

        result.getBody().setTotal(ChargingCableService.self().countJoinBySearch(search));
        List<ChargingCable> chargingCableList = ChargingCableService.self().findJoinBySearch(search, pageNo, pageLimit);
        if(chargingCableList != null && chargingCableList.size() > 0){
            result.setCode(DtoConstants.SUCCESS, null);
            result.getBody().setData(chargingCableList);
        }
        return result;
    }

    @Route("/pcl/device/add.html")
    public String add(HttpServletRequest request) {
        List<String> deviceTypeIds = DeviceTypeFuncService.self().findTypeIdByCode(EDeviceFunCode.PCL.index());
        if(deviceTypeIds != null && deviceTypeIds.size() > 0) {
            List<DeviceType> deviceTypeList = DeviceTypeService.self().findByIds(deviceTypeIds);
            request.setAttribute("deviceTypeList", deviceTypeList);
        }
        return "/pcl/device/edit.html";
    }

    @Route(value = { "/pcl/device/add.do" })
    public AjaxResult doAdd(HttpServletRequest request) {
        AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR, "新增充电插座主机失败");
        ChargingCable chargingCable = WebUtils.getParameter(request, ChargingCable.class);
        try {
            DeviceType deviceType = DeviceTypeService.self().getById(chargingCable.getDeviceTypeId());
            if(deviceType == null){
                result.setMsg("设备类型不存在");
                return result;
            }

            DeviceTypeFunc deviceTypeFunc = DeviceTypeFuncService.self()
                    .getByKeys(chargingCable.getDeviceTypeId(), EDeviceFunCode.PCL.index());
            if(deviceTypeFunc == null){
                result.setMsg("设备类型不存在此功能");
                return result;
            }
            chargingCable.setDeviceTypeName(deviceType.getName());
            chargingCable.setProtocolType(deviceTypeFunc.getProtocolType());
            if(ChargingCableService.self().add(chargingCable)){
                result.setCode(DtoConstants.SUCCESS,null);
            }
        } catch (LogicException e) {
            result.setMsg(e.getMessage());
        }
        return result;
    }

    @Route("/pcl/device/info.html")
    public String info(HttpServletRequest request) {
        String deviceSn = WebUtils.getString(request,"deviceSn");
        if(StringTools.isNotBlank(deviceSn)){
            ChargingCable chargingCable = ChargingCableService.self().getJoinByDeviceSn(deviceSn);
            if(chargingCable != null) {
                WebUtils.setAttribute(request, chargingCable);

                Device device = DeviceService.self().getByDeviceSn(chargingCable.getDeviceSn());
                if (device != null) {
                    request.setAttribute("device", device);
                }
            }
        }
        return "/pcl/device/info.html";
    }

    @Route(value = { "/pcl/device/work_state/check.do" })
    public AjaxResult doCheckWorkState(HttpServletRequest request) {
        AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR, "检查工作状态失败");
        try {
            BusyThreadPool.self().execute(new Runnable() {
                @Override
                public void run() {
                    ChargingCableService.self().checkWorkState();
                }
            });
            result.setCode(DtoConstants.SUCCESS,null);
        } catch (Exception e) {
            result.setMsg(e.getMessage());
        }
        return result;
    }

    @Route(value = { "/pcl/device/qrcode.html" })
    public String qrcode(HttpServletRequest request) {
        String deviceSn = WebUtils.getString(request, "deviceSn");
        if (StringUtils.isNotBlank(deviceSn)) {
            ChargingCable chargingCable = ChargingCableService.self().getByDeviceSn(deviceSn);
            if (chargingCable != null) {
                String httpDomain = PropertyTools.get().getString("httpDomain");
                String url = httpDomain + "/dev/pcl/" + chargingCable.getDeviceSn();
                request.setAttribute("url", url);
            }
        }
        return "/pcl/device/qrcode.html";
    }

    @Route(value = { "/pcl/device/qrcode.jpg" })
    public void qrcodeImg(HttpServletRequest request, HttpServletResponse response) {
        String deviceSn = WebUtils.getString(request, "deviceSn");
        if (StringUtils.isNotBlank(deviceSn)) {
            ChargingCable chargingCable = ChargingCableService.self().getByDeviceSn(deviceSn);
            if (chargingCable != null) {
                try {
                    String httpDomain = PropertyTools.get().getString("httpDomain");
                    String url = httpDomain + "/dev/pcl/" + chargingCable.getDeviceSn();
                    WebUtils.exportJPEG(response);
                    MatrixToImageWriter.writeToStream(url, 400, 300, "jpeg", response.getOutputStream());
                } catch (IOException e) {
                    log.error(e.getMessage(), e);
                }
            }
        }
    }

    @Route(value = { "/pcl/device/del.do" })
    public AjaxResult doDel(HttpServletRequest request) {
        AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR, "删除充电插座主机失败");
        String deviceSn = WebUtils.getString(request,"deviceSn");
        if(StringTools.isNotBlank(deviceSn)) {
            try {
                Device device = DeviceService.self().getByDeviceSn(deviceSn);
                if(device != null){
                    //检查设备类型对应的功能项
                    List<DeviceTypeFunc> deviceTypeFuncList = DeviceTypeFuncService.self().findByTypeId(device.getDeviceTypeId());
                    if(deviceTypeFuncList != null && deviceTypeFuncList.size() > 1) {
                        throw new LogicException("设备有"+deviceTypeFuncList.size()+"个功能项，请在设备索引列表中删除");
                    }
                    if(DeviceService.self().deleteByDeviceSn(deviceSn)){
                        result.setCode(DtoConstants.SUCCESS, null);
                    }
                }else {
                    if (ChargingCableService.self().deleteByDeviceSn(deviceSn)) {
                        result.setCode(DtoConstants.SUCCESS, null);
                    }
                }
            } catch (LogicException e) {
                result.setMsg(e.getMessage());
            }
        }
        return result;
    }
}
